package com.haohan.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.fluent.Request;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.haohan.stock.domain.StockData;

public class DataUtil {

	public final static String SINAURL = "http://money.finance.sina.com.cn/quotes_service/api/jsonp_v2.php/var%20_sh601766_30_1477639648668=/CN_MarketData.getKLineData?ma=no";

	/**
	 * 返回日线数据
	 * 
	 * @param stockcode
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static List<StockData> getStockData(String stockcode,long scale,long datalen) {
		List<StockData> stockdata_list = new ArrayList<StockData>();
		Boolean a = true;
		try {
			while (a) {
				Object obj = getData(stockcode, scale, datalen, stockdata_list);
				if (obj instanceof Boolean) {
					a = (Boolean) obj;
				} else {
					a = false;
					stockdata_list = (List<StockData>) obj;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return stockdata_list;
	}
	
	private static Object getData(String stockcode, long scale, long datalen, List<StockData> stockdata_list) {
		try {
			StringBuffer url = new StringBuffer(SINAURL);
			url.append("&symbol=");
			url.append(stockcode);
			url.append("&scale=");
			url.append(scale);
			url.append("&datalen=");
			url.append(datalen);
			Gson gson = new Gson();
			String result = Request.Get(url.toString()).connectTimeout(3000).socketTimeout(3000).execute()
					.returnContent().asString();
			String data = result.split("=")[1];
			if (data == null) {
				return false;
			}
			data = data.substring(1, data.length() - 1);
			stockdata_list = gson.fromJson(data, new TypeToken<List<StockData>>() {
			}.getType());
			return stockdata_list;
		} catch (Exception e) {
			return true;
		}
	}
	public static String objectToJson(Object list) {
		Gson gson = new GsonBuilder().create();
		return gson.toJson(list);
	}
	
}